package com.init.iblog.service.impl;

import com.google.gson.Gson;
import com.init.iblog.domain.ResponseResult;
import com.init.iblog.enums.AppHttpCodeEnum;
import com.init.iblog.exception.SystemException;
import com.init.iblog.service.UploadService;
import com.init.iblog.utils.PathUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Service
public class UploadServiceImpl implements UploadService {


    @Override
    public ResponseResult uploadImg(MultipartFile img) {

        //判断文件类型和文件大小
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断
        if(!originalFilename.endsWith(".jpg")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        //如果通过判断上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);


        System.out.println("==============filePath" + filePath);
        //返回上传后的外链地址
        String url = uploadOss(img,filePath);
        System.out.println("+++++++++++url"+url);
        return ResponseResult.okResult(url);
    }

    private String uploadOss(MultipartFile img,String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "HPoZRZXddULc8zyTbB7PHidbD3UgjWiFxUDERYj7";
        String secretKey = "qvjhxiLnmN8uwpr4-Na4QAJsTrWsFjvjHLzca13Q";
        String bucket = "iblog-cloudy2";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);


            //将前端传过来的文件转化为InputStream
            InputStream inputStream = img.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);

                //返回外链地址
                return "http://rtf4vwp7w.hd-bkt.clouddn.com//" + key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }


        //返回外链地址
        return "fail";
    }

}
